<?php
namespace App\Models;

use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;


# 部门
class Department extends Model
{

//    use ModelTree;

    protected $table = 'yt_department';
    public $timestamps = false;

    protected $fillable = [
        'name',
        'parent_id',
        'dept_id',  // 钉钉接口部门id
    ];

        /**
     * Build options of select field in form.
     *
     * @param array  $nodes
     * @param int    $parentId
     * @param string $prefix
     * @param string $space
     *
     * @return array
     */
    protected function buildSelectOptions(array $nodes = [], $parentId = 1, $prefix = '', $space = '&nbsp;'): array
    {
        $prefix = $prefix ?: '┝'.$space;

        $options = [];

        if (empty($nodes)) {
            $nodes = $this->allNodes();
        }

        foreach ($nodes as $index => $node) {
            if ($node[$this->parentColumn] == $parentId) {
                $node['name'] = $prefix.$space.$node['name'];

                $childrenPrefix = str_replace('┝', str_repeat($space, 6), $prefix).'┝'.str_replace(['┝', $space], '', $prefix);

                $children = $this->buildSelectOptions($nodes, $node['dept_id'], $childrenPrefix);
                $options[$node['dept_id']] = $node['name'];

                if ($children) {
                    $options += $children;
                }
            }
        }

        return $options;
    }

    // 获取部门
    static function getAllDept()
    {
        return Department::select()->pluck('name', 'dept_id')->toArray();

    }

    /**
     * 获取采购部已以下部门id集
    */
    public static function getPurchaseDeptIds(){
        $purchase_dept_id = Config::get('constants.PURCHASE_DEPT_ID');
        $ids = [$purchase_dept_id];
        //查询下级
        $next_ids = self::where('parent_id', $purchase_dept_id)->get(['dept_id'])->pluck('dept_id')->toArray();
        if( !empty($next_ids) ){
            $ids = array_merge($next_ids, $ids);
        }
        return $ids;
    }




}
